import { EnableRefType } from '@/types/common';
import { reactive, watch, toRefs, ref, unref } from 'vue'

export function useTable<R extends { list: any, total: number }, P extends object>(requestApi: (params: P) => PRT<R>, queryParams: EnableRefType<P>) {

    // table列表
    let tableData = ref<R['list']>([]);
    // 分页初始数据
    const pageData = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 0
    })

    // 将传入的对象参数 获取其值
    const queryObj = {} as P
    watch(
        () => queryParams,
        (newVal) => {
            for (let key in newVal) {
                queryObj[key] = unref(newVal[key]) as P[Extract<keyof P, string>]
            }
        },
        { deep: true }//立即监听
    );

    async function fetchData() {
        let res = await requestApi({
            pageNum: pageData.currentPage,
            pageSize: pageData.pageSize,
            ...queryObj,
        })
        if (res.code === 200) {
            tableData.value = res.data.list;
            pageData.total = res.data.total;
        }
    }
    // 获取初始化数据
    fetchData();

    // 设置分页器的初始化数据
    function handleSizeChange() {
        fetchData()
    }
    function handleCurrentChange() {
        // 根据当前的页面序号重新发送请求
        fetchData()
    }

    return {
        tableData,
        pageData,
        handleSizeChange,
        handleCurrentChange,
        fetchData
    }
}


